<template>
  <el-container class="layout-container">
    <CommonSidebar />

    <el-main class="main-container">
      <div class="admin-container">
        <div class="header">
          <h2>用户管理</h2>
          <el-input v-model="searchQuery" placeholder="搜索用户名/邮箱" prefix-icon="Search" class="search-input" />
        </div>

        <el-table :data="users" stripe style="width: 100%">
          <el-table-column prop="username" label="用户名" width="120" />
          <el-table-column prop="createdAt" label="注册时间" width="180" />
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button-group>
                <el-button type="danger" size="small" @click="deleteUser(row)">
                  删除用户
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next" class="pagination" />
      </div>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAdminStore } from "@/store/modules/admin";
import { timeFormat } from "@/utils/timeformat.js";
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const users = ref([])

const adminStore = useAdminStore();

// 获取用户列表
const fetchUsers = async () => {
  try {
    await adminStore.fetchUsers();
    // Object.entries(response).forEach(element => {
    //   console.log(element[0], element[1])
    // });
    const data = adminStore.users

    // 遍历对象,转换成数组
    users.value = Object.entries(data).map(([username, value]) => {
      const parsedValue = JSON.parse(value.replace(/'/g, '"'))
      const createdAt = timeFormat(parsedValue.find((item) =>
        item.hasOwnProperty("created_at")
      ).created_at);

      return { username, createdAt }
    })
    console.log(users.value)
    total.value = users.value.length;
  } catch (error) {
    console.log(error)
    ElMessage.error('获取用户列表失败')
  }
}

const deleteUser = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 ${user.username} 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await adminStore.deleteUser(user.username);
    ElMessage.success("删除成功");
    fetchUsers();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

// 切换用户状态
const toggleUserStatus = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要${user.status === 'active' ? '禁用' : '启用'}该用户吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await fetch(`/api/admin/users/${user.id}/status`, {
      method: 'PUT',
      body: JSON.stringify({
        status: user.status === 'active' ? 'disabled' : 'active'
      })
    })

    ElMessage.success('操作成功')
    fetchUsers()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 重置密码
const resetPassword = async (user) => {
  try {
    await ElMessageBox.confirm(
      '确定要重置该用户的密码吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await fetch(`/api/admin/users/${user.id}/reset-password`, {
      method: 'POST'
    })

    ElMessage.success('密码重置成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('密码重置失败')
    }
  }
}

// 查看用户详情
const viewUserDetails = (user) => {
  // 实现查看用户详情的逻辑
}

// 初始化加载
fetchUsers()
</script>

<style scoped>
.layout-container {
  height: 100vh;
  display: flex;
}

.main-container {
  flex: 1;
  background: #f5f7fa;
}

.admin-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-button-group {
  .el-button {
    margin-right: 8px;
  }
}
</style>
